/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package graficotestearquivo3;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.GridLayout;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.InputMismatchException;
import java.util.Scanner;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.dial.DialBackground;
import org.jfree.chart.plot.dial.DialCap;
import org.jfree.chart.plot.dial.DialPlot;
import org.jfree.chart.plot.dial.DialTextAnnotation;
import org.jfree.chart.plot.dial.DialValueIndicator;
import org.jfree.chart.plot.dial.StandardDialFrame;
import org.jfree.chart.plot.dial.StandardDialScale;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.data.general.ValueDataset;
import org.jfree.ui.GradientPaintTransformType;
import org.jfree.ui.StandardGradientPaintTransformer;

/**
 *
 * @author saulomedeiros
 */
public class DialDemo1 extends javax.swing.JFrame {

   static class DemoPanelB extends JPanel
                implements ChangeListener
        {       private static int idparameter;

                DefaultValueDataset dataset;
                JSlider slider;
                 public static int getIdparameter(){
                    return DemoPanelB.idparameter;
                 }
                public static JFreeChart createStandardDialChart(String s, String s1, ValueDataset valuedataset, double d, double d1, double d2, int i)
                {
                        DialPlot dialplot = new DialPlot();
                        dialplot.setDataset(valuedataset);
                        dialplot.setDialFrame(new StandardDialFrame());
                        dialplot.setBackground(new DialBackground());
                        DialTextAnnotation dialtextannotation = new DialTextAnnotation(s1);
                        dialtextannotation.setFont(new Font("Dialog", 1, 14));
                        dialtextannotation.setRadius(0.69999999999999996D);
                        dialplot.addLayer(dialtextannotation);
                        DialValueIndicator dialvalueindicator = new DialValueIndicator(0);
                        dialplot.addLayer(dialvalueindicator);
                        StandardDialScale standarddialscale = new StandardDialScale(d, d1, -120D, -300D, 10D, 4);
                        standarddialscale.setMajorTickIncrement(d2);
                        standarddialscale.setMinorTickCount(i);
                        standarddialscale.setTickRadius(0.88D);
                        standarddialscale.setTickLabelOffset(0.14999999999999999D);
                        standarddialscale.setTickLabelFont(new Font("Dialog", 0, 14));
                        dialplot.addScale(0, standarddialscale);
                        dialplot.addPointer(new org.jfree.chart.plot.dial.DialPointer.Pin());
                        DialCap dialcap = new DialCap();
                        dialplot.setCap(dialcap);
                        return new JFreeChart(s, dialplot);
                }

                 public void stateChanged(ChangeEvent changeevent)
                {
                        dataset.setValue(new Integer(slider.getValue()));
                }
                public static void InserirDialchart(String linha, int iddialchart){// inserir no banco de dados
                PreparedStatement ps = null;
                Connection conn = null;
                Statement st = null;
                Scanner teclado=new Scanner(System.in);
                try{
                     DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                     conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                     ps = conn.prepareStatement("insert into dialchartdata (idparameter,iddialchart,dialvalue,scale) VALUES (?,?,?,?) ");
                     st=conn.createStatement();
                     ResultSet rs=st.executeQuery("select max(idparameter) from parameter");
                     while(rs.next()){
                        idparameter=rs.getInt(1);
                     }
                                System.out.print("\nidparameter:");
                                ps.setInt(1, idparameter);
                                System.out.print("\niddialchart:");
                                ps.setInt(2, iddialchart);
                                System.out.print("\ndialvalue:");
                                ps.setString(3,linha);
                                System.out.print("\nscale");
                                ps.setDouble(4,1000000);
                                ps.executeUpdate();
                        
                 }catch(InputMismatchException e){
                     System.out.println(e.getMessage());
                 }catch(SQLException e){
                     System.out.println(e.getMessage());
                 }finally{
                    try {
                        ps.close();
                        conn.close();
                    } catch (SQLException ex) {
                        System.out.println(ex.getMessage());
                    }

                 }
        }
                //@overwrite
                public DemoPanelB(int qntelementos,int execution){
                    super(new BorderLayout());
                    String[] parts;
                    Double[] partsdouble= new Double[1];
                    int num;
                    try{    
                    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                    Statement st = conn.createStatement();
                    num=DemoPanelB.getIdparameter()-qntelementos+execution+1;
                    System.out.println("subtracao demopanelB:"+num);
                    ResultSet rs = st.executeQuery("select * from dialchartdata  where idparameter="+num);
                    while(rs.next()){
                        String value = rs.getString(4);
                        if(rs.getInt(3)%2==0)
                            partsdouble[0]=Double.parseDouble(value);
                        /*for(int i=0;i<parts.length;i++){
                            System.out.print("\nindex:"+i);
                            System.out.print("\nParts:"+parts[i]);
                        }
                        System.out.print("\n2 loop");*/    
                    }
                    dataset = new DefaultValueDataset(partsdouble[0]);
                    JFreeChart jfreechart = createStandardDialChart("Dial Demo 1", "Temperature", dataset, 0D, 1000000D, 500000D, 4);
                    DialPlot dialplot = (DialPlot)jfreechart.getPlot();
                    GradientPaint gradientpaint = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(), new Color(170, 170, 220));
                    DialBackground dialbackground = new DialBackground(gradientpaint);
                    dialbackground.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
                    dialplot.setBackground(dialbackground);
                    dialplot.removePointer(0);
                    dialplot.addPointer(new org.jfree.chart.plot.dial.DialPointer.Pointer());
                    ChartPanel chartpanel = new ChartPanel(jfreechart);
                    chartpanel.setPreferredSize(new Dimension(400, 400));
                    slider = new JSlider(-40, 60);
                    slider.setMajorTickSpacing(10);
                    slider.setPaintLabels(true);
                    slider.addChangeListener(this);
                        add(chartpanel);
                    }catch(SQLException e){
                        e.printStackTrace();
                    }    
                }
                public DemoPanelB(String txtB)
                {
                        super(new BorderLayout());
                        String[] parts;
                          //BufferedReader br=null;
                          Double[] partsdouble= new Double[1];
                
                         try {  
			   File arquivo = new File(txtB);  
			   FileInputStream   fileInputStream = new FileInputStream(arquivo);  
			   InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);  
			   LineNumberReader  lineNumberReader= new LineNumberReader(inputStreamReader);
                           StringBuilder sb = new StringBuilder();
			   String linha;  
			   

			   while(lineNumberReader.ready()) {  
				   int ln = lineNumberReader.getLineNumber();
				   linha = lineNumberReader.readLine(); 
				   if( ln==37){
                                           sb.append(linha);
                                           InserirDialchart(linha,2);
                                           //sb.append("\n");
					   System.out.println("linha-grafico dial:"+ln);
					   System.out.println(linha);  
				   }   
			   }
                           
                            String everything = sb.toString();
                            parts = everything.split(",");
                            partsdouble[0]=Double.parseDouble(parts[0]);    
                        }catch(FileNotFoundException e){
                              System.out.println(e.getMessage());
                        }catch(IOException e){
                              System.out.println(e.getMessage());
                        } 
                        dataset = new DefaultValueDataset(partsdouble[0]);
                        JFreeChart jfreechart = createStandardDialChart("Dial Demo 1", "Temperature", dataset, 0D, 1000000D, 500000D, 4);
                        DialPlot dialplot = (DialPlot)jfreechart.getPlot();
                        /*StandardDialRange standarddialrange = new StandardDialRange(40D, 60D, Color.red);
                        standarddialrange.setInnerRadius(0.52000000000000002D);
                        standarddialrange.setOuterRadius(0.55000000000000004D);
                        dialplot.addLayer(standarddialrange);
                        StandardDialRange standarddialrange1 = new StandardDialRange(10D, 40D, Color.orange);
                        standarddialrange1.setInnerRadius(0.52000000000000002D);
                        standarddialrange1.setOuterRadius(0.55000000000000004D);
                        dialplot.addLayer(standarddialrange1);
                        StandardDialRange standarddialrange2 = new StandardDialRange(-40D, 10D, Color.green);
                        standarddialrange2.setInnerRadius(0.52000000000000002D);
                        standarddialrange2.setOuterRadius(0.55000000000000004D);
                        dialplot.addLayer(standarddialrange2);*/
                        GradientPaint gradientpaint = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(), new Color(170, 170, 220));
                        DialBackground dialbackground = new DialBackground(gradientpaint);
                        dialbackground.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
                        dialplot.setBackground(dialbackground);
                        dialplot.removePointer(0);
                        dialplot.addPointer(new org.jfree.chart.plot.dial.DialPointer.Pointer());
                        ChartPanel chartpanel = new ChartPanel(jfreechart);
                        chartpanel.setPreferredSize(new Dimension(400, 400));
                        slider = new JSlider(-40, 60);
                        slider.setMajorTickSpacing(10);
                        slider.setPaintLabels(true);
                        slider.addChangeListener(this);
                        add(chartpanel);
                        //add(slider, "South");
                }

        }

        static class DemoPanelA extends JPanel
                implements ChangeListener
        {       private static int idparameter;

                JSlider slider;
                DefaultValueDataset dataset;
                
                public static int getIdparameter(){
                    return DemoPanelA.idparameter;
                }
                public static JFreeChart createStandardDialChart(String s, String s1, ValueDataset valuedataset, double d, double d1, double d2, int i)
                {
                        DialPlot dialplot = new DialPlot();
                        dialplot.setDataset(valuedataset);
                        dialplot.setDialFrame(new StandardDialFrame());
                        dialplot.setBackground(new DialBackground());
                        DialTextAnnotation dialtextannotation = new DialTextAnnotation(s1);
                        dialtextannotation.setFont(new Font("Dialog", 1, 14));
                        dialtextannotation.setRadius(0.69999999999999996D);
                        dialplot.addLayer(dialtextannotation);
                        DialValueIndicator dialvalueindicator = new DialValueIndicator(0);
                        dialplot.addLayer(dialvalueindicator);
                        StandardDialScale standarddialscale = new StandardDialScale(d, d1, -120D, -300D, 10D, 4);
                        standarddialscale.setMajorTickIncrement(d2);
                        standarddialscale.setMinorTickCount(i);
                        standarddialscale.setTickRadius(0.88D);
                        standarddialscale.setTickLabelOffset(0.14999999999999999D);
                        standarddialscale.setTickLabelFont(new Font("Dialog", 0, 14));
                        dialplot.addScale(0, standarddialscale);
                        dialplot.addPointer(new org.jfree.chart.plot.dial.DialPointer.Pin());
                        DialCap dialcap = new DialCap();
                        dialplot.setCap(dialcap);
                        return new JFreeChart(s, dialplot);
                }

                public void stateChanged(ChangeEvent changeevent)
                {
                        dataset.setValue(new Integer(slider.getValue()));
                }
                public static void InserirDialchart(String linha, int iddialchart){// inserir no banco de dados
                PreparedStatement ps = null;
                Connection conn = null;
                Statement st = null;
                Scanner teclado=new Scanner(System.in);
                try{
                     DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                     conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                     ps = conn.prepareStatement("insert into dialchartdata (idparameter,iddialchart,dialvalue,scale) VALUES (?,?,?,?) ");
                     st=conn.createStatement();
                     ResultSet rs=st.executeQuery("select max(idparameter) from parameter");
                     while(rs.next()){
                        idparameter=rs.getInt(1);
                     }
                                System.out.print("\nidparameter:");
                                ps.setInt(1, idparameter);
                                System.out.print("\niddialchart:");
                                ps.setInt(2, iddialchart);
                                System.out.print("\ndialvalue:");
                                ps.setString(3,linha);
                                System.out.print("\nscale");
                                ps.setDouble(4,1000000);
                                ps.executeUpdate();
                        
                 }catch(InputMismatchException e){
                     System.out.println(e.getMessage());
                 }catch(SQLException e){
                     System.out.println(e.getMessage());
                 }finally{
                    try {
                        ps.close();
                        conn.close();
                    } catch (SQLException ex) {
                        System.out.println(ex.getMessage());
                    }

                 }
        }
                   //@overwrite
                public DemoPanelA(int qntelementos,int execution){
                    super(new BorderLayout());
                    String[] parts;
                    Double[] partsdouble= new Double[1];
                    int num;
                    try{    
                    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                    Statement st = conn.createStatement();
                    num=DemoPanelA.getIdparameter()-qntelementos+execution+1;
                    System.out.println("subtracao demopanelA:"+num);
                    ResultSet rs = st.executeQuery("select * from dialchartdata  where idparameter="+num);
                    while(rs.next()){
                        String value = rs.getString(4);
                        if(rs.getInt(3)%2!=0)
                            partsdouble[0]=Double.parseDouble(value);
                        /*for(int i=0;i<parts.length;i++){
                            System.out.print("\nindex:"+i);
                            System.out.print("\nParts:"+parts[i]);
                        }
                        System.out.print("\n2 loop");*/    
                    }
                    dataset = new DefaultValueDataset(partsdouble[0]);
                    JFreeChart jfreechart = createStandardDialChart("Dial Demo 1", "Temperature", dataset, 0D, 1000000D, 500000D, 4);
                    DialPlot dialplot = (DialPlot)jfreechart.getPlot();
                    GradientPaint gradientpaint = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(), new Color(170, 170, 220));
                    DialBackground dialbackground = new DialBackground(gradientpaint);
                    dialbackground.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
                    dialplot.setBackground(dialbackground);
                    dialplot.removePointer(0);
                    dialplot.addPointer(new org.jfree.chart.plot.dial.DialPointer.Pointer());
                    ChartPanel chartpanel = new ChartPanel(jfreechart);
                    chartpanel.setPreferredSize(new Dimension(400, 400));
                    slider = new JSlider(-40, 60);
                    slider.setMajorTickSpacing(10);
                    slider.setPaintLabels(true);
                    slider.addChangeListener(this);
                        add(chartpanel);
                    }catch(SQLException e){
                        e.printStackTrace();
                    }    
                }
                public DemoPanelA(String txtA)
                {
                      
                        super(new BorderLayout());
                          String[] parts;
                          //BufferedReader br=null;
                          Double[] partsdouble= new Double[1];
                
                         try {  
			   File arquivo = new File(txtA);  
			   FileInputStream   fileInputStream = new FileInputStream(arquivo);  
			   InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);  
			   LineNumberReader  lineNumberReader= new LineNumberReader(inputStreamReader);
                           StringBuilder sb = new StringBuilder();
			   String linha;  
			   

			   while(lineNumberReader.ready()) {  
				   int ln = lineNumberReader.getLineNumber();
				   linha = lineNumberReader.readLine(); 
				   if( ln==36){
                                           sb.append(linha);
                                           InserirDialchart(linha,1);
                                           //sb.append("\n");
					   System.out.println("linha-grafico dial:"+ln);
					   System.out.println(linha);  
				   }   
			   }
                           
                            String everything = sb.toString();
                            parts = everything.split(",");
                            partsdouble[0]=Double.parseDouble(parts[0]);    
                        }catch(FileNotFoundException e){
                              System.out.println(e.getMessage());
                        }catch(IOException e){
                              System.out.println(e.getMessage());
                        }   
                        dataset = new DefaultValueDataset(partsdouble[0]);
                        JFreeChart jfreechart = createStandardDialChart("Dial Demo 1", "Temperature", dataset, 0D, 1000000D, 500000D, 4);
                        DialPlot dialplot = (DialPlot)jfreechart.getPlot();
                        /*StandardDialRange standarddialrange = new StandardDialRange(40D, 60D, Color.red);
                        standarddialrange.setInnerRadius(0.52000000000000002D);
                        standarddialrange.setOuterRadius(0.55000000000000004D);
                        dialplot.addLayer(standarddialrange);
                        StandardDialRange standarddialrange1 = new StandardDialRange(10D, 40D, Color.orange);
                        standarddialrange1.setInnerRadius(0.52000000000000002D);
                        standarddialrange1.setOuterRadius(0.55000000000000004D);
                        dialplot.addLayer(standarddialrange1);
                        StandardDialRange standarddialrange2 = new StandardDialRange(-40D, 10D, Color.green);
                        standarddialrange2.setInnerRadius(0.52000000000000002D);
                        standarddialrange2.setOuterRadius(0.55000000000000004D);
                        dialplot.addLayer(standarddialrange2);*/
                        GradientPaint gradientpaint = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(), new Color(170, 170, 220));
                        DialBackground dialbackground = new DialBackground(gradientpaint);
                        dialbackground.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
                        dialplot.setBackground(dialbackground);
                        dialplot.removePointer(0);
                        dialplot.addPointer(new org.jfree.chart.plot.dial.DialPointer.Pointer());
                        ChartPanel chartpanel = new ChartPanel(jfreechart);
                        chartpanel.setPreferredSize(new Dimension(400, 400));
                        slider = new JSlider(-40, 60);
                        slider.setMajorTickSpacing(10);
                        slider.setPaintLabels(true);
                        slider.addChangeListener(this);
                        add(chartpanel);
                        //add(slider, "South");
                }
                

        }


        public DialDemo1()
        {
                //super(s);
                setDefaultCloseOperation(3);
                setContentPane(createDemoPanel());
        }
        
         public static JPanel createDemoPanel(int num1,int numero)
        {
                JPanel jpanel = new JPanel(new GridLayout(1, 2));
                jpanel.add(new DemoPanelA(num1,numero));
                jpanel.add(new DemoPanelB(num1,numero));
                return jpanel;
        }
        public static JPanel createDemoPanel()
        {
                /*Scanner teclado = new Scanner(System.in);
                System.out.print("Digite o arquivo para Dial A:");
                String txtA=teclado.nextLine();
                System.out.print("Digite o arquivo para Dial B:");
                String txtB=teclado.nextLine();*/
                JPanel jpanel = new JPanel(new GridLayout(1, 2));
                jpanel.add(new DemoPanelA("arquivo01.txt"));
                jpanel.add(new DemoPanelB("arquivo01.txt"));
                return jpanel;
        }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 147, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(0, 153, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DialDemo1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DialDemo1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DialDemo1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DialDemo1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DialDemo1().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
}
